from datetime import datetime
from flask import Blueprint, request, current_app
from utilsapp.common import assign_value, parsing_data_id
from utilsapp.mysql_con import (
    db_delete,
    db_insert,
    db_table_pagelist,
    db_update,
    db_list,
    db_pagelist,
)
import utilsapp
import pymysql, traceback

bluePrint = Blueprint("diagnosis", __name__)
tableName = "diagnosis"


@bluePrint.route("/tree", methods=["post"])
def a():
    scoped = parsing_data_id(None, request)
    scoped = "" if len(scoped) <= 0 else f"where {scoped}"
    index_d = request.args.get("id")
    try:
        debug = assign_value(request.json, "debug")
    except Exception as e:
        debug = ""
    if index_d is None:
        index_d = 0
    s0 = f"""SELECT 
    id as value,
    parent as pid,
    name as label,
    type 
FROM 
    regionlevel 
ORDER BY
sort asc, 
    CASE 
        WHEN type = 'zone' THEN name 
        ELSE id 
    END asc, name asc"""
    res = db_list(s0)
    s0 = f"""
   select * from (
		SELECT CONCAT('d',d.id)  as `key`,d.id as value,concat('zone',d.zone_id) as pid,d.device_name as label,'d'  as type,IFNULL(MAX_warn_level,0) as MAX_warn_level,d.`status`,dt.icon,
        "" as address ,"" as port
        FROM device d
		LEFT JOIN (SELECT MAX(warn_level) as MAX_warn_level,device_id from warn where is_show=1 and notice not in (2,3,4) GROUP BY device_id) w1 on w1.device_id = d.id
		LEFT JOIN device_type dt on dt.id = d.type_id
        {scoped}
		UNION ALL
		
		SELECT CONCAT('s',s.id)  as `key`,s.id as value,concat('d',s.device_id),s.sensor_name,'s' as type,warn_level,`status`,st.icon ,
        s.address,s.port
        FROM sensor s
		LEFT JOIN (SELECT MAX(warn_level) as warn_level,sensor_id from warn where is_show=1 and notice not in (2,3,4) GROUP BY sensor_id) w on w.sensor_id = s.id
		LEFT JOIN sensor_type st on st.id = s.sensor_type
        {scoped}
   ) as a ORDER BY value ASC
    """
    device_data = db_list(s0)["data"]
    res_data = res.get("data")
    p = next((t for t in res_data if t["value"] == int(index_d)), None)
    if p is None and index_d != 0:
        return utilsapp.utils.fail(data=[])
    tdata = res_data + device_data
 
    res = build_tree1(tdata, 0, debug)
    return utilsapp.common.ok(res)


@bluePrint.route("/temperature", methods=["post"])
def temperature():
    type = assign_value(request.json, "type")
    id = assign_value(request.json, "id")
    if type == "d":
        sql = f"""SELECT * from sensor where device_id = {id} """
    if type == "s":
        sql = f"""SELECT * from sensor where id = {id} """
    list = db_pagelist(sql, 1, 9999)["data"]
    conn = get_conn("ieplat")
    cur = conn.cursor()
    today = datetime.today()
    year = today.year
    month = today.month if today.month > 9 else "0" + str(today.month)
    for item in list:
        try:
            name = f'd_{item["port"]}_{item["address"]}_{year}{month}'
            q = f"""SELECT * FROM {name} WHERE feature_key = 'temperature' and time = (SELECT MAX(time) FROM {name})"""
            cur.execute(q)
            datas = cur.fetchall()
            fields = [field[0] for field in cur.description]
            s = [dict(zip(fields, result)) for result in datas]
            item["name"] = name
            item["temperature"] = None
            item["time"] = None
            if len(s) > 0:
                item["temperature"] = s[0]["value"]
                item["time"] = s[0]["time"]
        except Exception as e:

            cur.close()
            return db_pagelist(sql, 1, 9999)
    cur.close()
    return {"code": 0, "data": list}


def build_tree1(data, parent_id=None, de1=None):
    de11 = de1
    tree = []
    icon = ""
    debug = ""
    key = ""
    for item in data:
        if item["pid"] == parent_id:
            _pid = (
                item["type"] + str(item["value"])
                if item["type"] in ["zone", "d", "s"]
                else item["value"]
            )
            tts = ["group", "company", "factory", "zone", "d", "s"]
            tis = [
                "iconfont icon-jituan",
                "iconfont icon-gongsi",
                "iconfont icon-factory-full",
                "iconfont icon-gongchang",
                "iconfont",
                "iconfont",
            ]
            itype = item["type"].strip()
            icon = tis[tts.index(itype)]
            icon += (
                f" level-{0 if item['MAX_warn_level'] is None else item['MAX_warn_level']}"
                if item["type"] == "d"
                else ""
            )
            if item["type"] == "d":
                icon += f" {item['icon']}"
                key = f"{item['type'] }{ item['value']}"
            if item["type"] == "s":
                key = f"{item['type'] }{ item['value']}"
                s_status = "1" if item["status"] == "在线" else "3"
                s_status = (
                    f'2 level-{item["MAX_warn_level"]}'
                    if item["MAX_warn_level"]
                    else s_status
                )
                icon += (
                    f" {item['icon']} status-{s_status}  level-{item['MAX_warn_level']}"
                )
                debug = item["port"] + "/" + item["address"] if de1 == 1 else ""
                # print("debug",debug)
            node = {
                "value": item["value"],
                "label": f"{ item['label']}{debug}",
                "type": itype,
                "pid": item["pid"],
                "icon": icon,
                "children": (
                    [] if itype == "s" else build_tree1(data, parent_id=_pid, de1=de11)
                ),
            }
            if item["type"] in ["d", "s"]:
                node.update({"key": key})
            if len(node["children"]) > 0 or itype in ["s"]:
                tree.append(node)

    if len(tree) == 1 and tree[0]["type"] not in ["d", "s","factory"]:
        return tree[0]["children"]
    return tree


def get_conn(db_name=None, dbconfig=None):
    d = current_app.config["settings"]["mysql"]
    db_name = d["dbname"] if db_name is None else db_name
    dbconfig = d if dbconfig is None else dbconfig
    return pymysql.connect(
        host=dbconfig["host"],
        user=dbconfig["user"],
        port=dbconfig["port"],
        password=dbconfig["password"],
        db=db_name,
        charset="utf8",
        connect_timeout=10,
        read_timeout=10,
        write_timeout=10,
    )
